<template>
  <div class="login-page">
    <van-nav-bar title="登录" />

    <van-tabs v-model="loginWay">
      <van-tab title="密码登录" name="password"></van-tab>
      <van-tab title="验证码登录" name="code"></van-tab>
    </van-tabs>

    <br />
    <div v-show="loginWay === 'password'">
      <van-field
        v-model="params.account"
        name="account"
        label="账号"
        placeholder="账号"
        :rules="[
          { required: true, message: '请填写用户名' },
          { pattern: /^\w{4,}$/, message: '请输入至少4位的用户名' },
        ]"
      />
      <van-field
        v-model="params.password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\w{6,}$/, message: '请输入至少6位的密码' },
        ]"
      />
    </div>
    <div v-show="loginWay === 'code'">
      <van-field
        v-model="params.email"
        type="email"
        name="email"
        label="邮箱"
        placeholder="邮箱"
        :rules="[{ required: true, message: '请填写邮箱' }]"
      />
      <van-field
        v-model="params.code"
        type="code"
        name="code"
        label="验证码"
        placeholder="验证码"
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /^\w{6,}$/, message: '请输入6位验证码' },
        ]"
      >
        <template #button>
          <van-button
            :disabled="timeCount !== 0"
            size="small"
            plain
            type="info"
            @click="sendCode"
            >{{
              timeCount === 0 ? "发送验证码" : `${timeCount}秒后可再次发送`
            }}</van-button
          >
        </template>
      </van-field>
    </div>
    <div style="margin: 16px">
      <van-button round block type="info" @click="handlelogin">登录</van-button>

      <router-link class="link" to="/register">注册账号</router-link>
      <!-- <button @click="ceshilogin">测试登录</button>
        <button @click="ceshi">点击测试</button> -->
    </div>
  </div>
</template>

<script>
/* eslint-disable */
/* eslint-disable */
import { Toast } from "vant";
import {
  visitor_login,
  visitor_page,
  ceshiApi2,
  ceshiApi,
  ceshiApi_visitor_login,
  visitor_logout,
  visitor_register,
  rate_add,
  rate_update,
  rate_delete,
  rate_page,
  visitor_add,
  visitor_detele,
  place_add,
  place_update,
  place_delete,
  place_page,
  send_email,
  gate_add,
  gate_update,
  gate_delete,
  gate_page,
  recommend_add,
  recommend_update,
  recommend_delete,
  recommend_page,
  address_add,
  address_update,
  address_delete,
  address_page,
  car_add,
  car_update,
  car_delete,
  car_page,
  comment_add,
  comment_update,
  comment_delete,
  comment_page,
  loveTotal_add,
  loveTotal_update,
  loveTotal_delete,
  loveTotal_page,
  loveCount_add,
  loveCount_update,
  loveCount_delete,
  loveCount_page,
  starCount_add,
  starCount_update,
  starCount_delete,
  starCount_page,
  starTotal_add,
  starTotal_update,
  starTotal_delete,
  starTotal_page,
  verificationCode_add,
  verificationCode_update,
  verificationCode_delete,
  verificationCode_page,
  tips_add,
  tips_update,
  tips_delete,
  tips_page,
  appeal_add,
  appeal_update,
  appeal_delete,
  appeal_page,
} from "@/api/index";
import { generateVerificationCode } from "@/utils";
import { setToken } from "@/utils/storage";
import { saveLocal, getLocal } from "@/utils/index";
export default {
  name: "login-page",
  data() {
    return {
      timeCount: 0, // 设置验证码重新发送的倒计时
      params: {
        account: "",
        password: "",
        email: "",
        code: "",
      },
      loginWay: "password",
      randomCode: undefined, // 用于保存验证码
      timeout: null, // 验证码过期计时器
      visitorList: {},
    };
  },
  methods: {
    // 发送验证码
    async sendCode() {
      if (this.timeout) {
        console.log("清空timeout");
        clearTimeout(this.timeout);
        this.timeout = null;
      }
      if (!this.params.email) {
        return Toast.fail("请先输入邮箱");
      }
      this.randomCode = generateVerificationCode();
      // console.log("randomCode", this.randomCode);
      // 5分钟后清除验证码
      this.timeout = setTimeout(() => {
        this.randomCode = undefined;
        // console.log('清空randomCode');
      }, 300000);
      this.timeCount = 10;
      const timerId = setInterval(() => {
        this.timeCount = this.timeCount - 1;
        if (this.timeCount === 0) {
          clearInterval(timerId);
        }
      }, 1000);
      await send_email({
        to: this.params.email,
        subject: "港城大学访客预约平台 -- 验证码",
        content: `亲爱的访客，您本次登录的验证码为${this.randomCode},该验证码5分钟内有效，请及时使用！！  -- 来自港城大学访客预约平台`,
      });
    },
    async handlelogin() {
      console.log("本次登录方式为:", this.loginWay);
      // 密码登录
      let payload = {};
      if (this.loginWay === "password") {
        payload = {
          username: this.params.account,
          password: this.params.password,
        };
      }
      // 验证码登录
      else {
        if (+this.params.code !== this.randomCode) {
          return Toast.fail("请输入正确的验证码");
        }
        const temp = this.visitorList.find(
          (item) => item.email === this.params.email
        );
        console.log("temp", temp);
        payload = {
          username: temp.account,
          password: temp.password,
        };
      }
      const res = await visitor_login(payload);
      if (res.code == 0) {
        setToken(res.token);
        Toast.success("登录成功");
        // 跳转至主页
        console.log(this.params);
        const res2 = await visitor_page(this.params.account);
        console.log("res2", res2);
        saveLocal("visitorData", res2.data.list[0]);
        this.$router.push("/");
      } else {
        return Toast.fail(res.msg);
      }
    },
    async ceshi() {
      const res = await appeal_page();
    },
    async ceshilogin() {
      const res = await ceshiApi_visitor_login();
      setToken(res.token);
    },
    async onSubmit(values) {
      console.log("submit", values);
      const { data: res } = await login(values);
      // console.log(res)
      setToken(res.token);
      Toast.success("登录成功");
      this.$router.push("/");
    },
    onClickLeft() {
      Toast("返回");
    },
    onClickRight() {
      Toast("按钮");
    },
  },
  async created() {
    const res = await visitor_page();
    this.visitorList = res.data.list;
    console.log("visitorList", this.visitorList);
  },
};
</script>

<style lang="less" scoped>
.link {
  margin-top: 10px;
  color: #069;
  font-size: 12px;
  padding-right: 20px;
  float: right;
}
</style>
